package com.example.certificate.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.certificate.dto.BasePageDTO;
import com.example.certificate.dto.InsResourceDto;
import com.example.certificate.dto.common.DelByIdDto;
import com.example.certificate.dto.common.DisableStatDto;
import com.example.certificate.entity.*;
import com.example.certificate.execption.BusinessException;
import com.example.certificate.mapper.SysResourceMapper;
import com.example.certificate.mapper.SysRouterAuthMapper;
import com.example.certificate.service.SysResourceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.certificate.service.SysRouterAuthService;
import com.example.certificate.utils.NodeTreeUtil;
import com.example.certificate.utils.ResultConstant;
import com.example.certificate.utils.ResultEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 菜单表	 服务实现类
 * </p>
 *
 * @author hao
 * @since 2022-02-16 11:29:59
 */
@Service
public class SysResourceServiceImpl extends ServiceImpl<SysResourceMapper, SysResource> implements SysResourceService {

    @Autowired
    private SysRouterAuthService authService;

    @Resource
    private SysResourceMapper sysResourceMapper;

    @Resource
    private SysRouterAuthMapper sysRouterAuthMapper;

    @Override
    public List<SysResource> routingHop(User user) {
        List<SysResource> myPerm = sysResourceMapper.getMyPerm(user.getRoleId());
        return  NodeTreeUtil.nodeTress(myPerm);
        //return  NodeTreeUtil.nodeTress(sysResourceMapper.selectList(new QueryWrapper<SysResource>().eq("enable_", 1)));
    }

    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW)
    public ResultEntity insSysResource(InsResourceDto dto) throws BusinessException {
        SysResource sysResource = new SysResource();
        BeanUtils.copyProperties(dto,sysResource);
        if(sysResourceMapper.insert(sysResource) > 0){
            if(!CollectionUtils.isEmpty(dto.getAuthor())){
                authService.saveBatch(authService.setRouterAuth(dto.getAuthor(),sysResource.getId()),5);
            }
        }else {
            throw new BusinessException(ResultConstant.ADD_FAIL.resultCode,"数据写入失败，请稍后重试");
        }
        return new ResultEntity("操作成功!");
    }

    @Override
    public List<SysResource> selAllRouter() {
        List<SysResource> sysResource = sysResourceMapper.selectList(new QueryWrapper<SysResource>().eq("enable_",1));
        sysResource.stream().forEach(item ->item.setMeta(JSONObject.parseObject(item.getMetaDesc(), Meta.class)));
        return sysResource;
    }

    @Override
    public List<Tree> getTreeResource() {
        return NodeTreeUtil.getResourceTree(sysResourceMapper.getTree(),true,sysRouterAuthMapper);
    }

    @Override
    public Page<SysResource> getResourcePage(BasePageDTO dto) {
        Page<SysResource> page = new Page<>();
        page.setCurrent(dto.getCurrent() == null ? 1 : dto.getCurrent());
        page.setSize(dto.getPageSize() == null ? 10 : dto.getPageSize());
        Page<SysResource> resourcePage = new Page<>();

        resourcePage = sysResourceMapper.routerPages(page,dto.getContent(),dto.getEmailString());

        for (SysResource resource:
                resourcePage.getRecords()) {
            resource.setMeta(JSONObject.parseObject(resource.getMetaDesc(),Meta.class));
        }
        return resourcePage;
    }

    @Override
    public ResultEntity updateStatus(DisableStatDto dto) {
        if(sysResourceMapper.updateStatus(dto.getId(),dto.getStatus()) > 0){
            return new ResultEntity("操作成功");
        }
        return new ResultEntity(ResultConstant.EDIT_FAIL);
    }

    @Override
    public ResultEntity delById(DelByIdDto dto) {
        if(sysResourceMapper.selectCount(new QueryWrapper<SysResource>().eq("parent_id",dto.getId())) > 0){
            return new ResultEntity(ResultConstant.DEL_SON_ROUTER_ERROR);
        }

        if(sysResourceMapper.deleteById(dto.getId()) > 0){
            return  new ResultEntity();
        }

        return new ResultEntity(ResultConstant.DELETE_FAIL);
    }

    @Override
    public SysResource getResourceById(DelByIdDto dto) {
        SysResource sysResource = sysResourceMapper.selectOne(new QueryWrapper<SysResource>().eq("id", dto.getId()));
        Meta meta = JSONObject.parseObject(sysResource.getMetaDesc(), Meta.class);
        meta.setJurisdictionList(authService.getRouterAuth(sysResource.getId()));
        sysResource.setMeta(meta);
        return sysResource;
    }

    @Override
    public ResultEntity updateResource(SysResource resource) {
        Meta meta = resource.getMeta();
        delOldData(resource.getId());
        if(!CollectionUtils.isEmpty(meta.getJurisdictionList())){
            authService.saveBatch(authService.setRouterAuth(meta.getJurisdictionList(),resource.getId()),5);
        }
        meta.setJurisdictionList(null);
        resource.setLabel(meta.getTitle());
        resource.setMetaDesc(JSONObject.toJSONString(meta));
        Integer updateStatus = sysResourceMapper.updateById(resource);
        if(updateStatus > 0){
            return new ResultEntity();
        }
        return new ResultEntity(ResultConstant.USER_DISABLE);
    }

    @Override
    public List<Tree> getAuthAllocation() {
        return NodeTreeUtil.getResourceTree(sysResourceMapper.getTree(),false,sysRouterAuthMapper);
    }

    /**
     * @Author Hao
     * @Description  删除数据库中之前的数据
     * @Date 2022/1/4
     * @Param [routerId]
     * @return void
     **/
    public void delOldData(String routerId){
        authService.remove(new QueryWrapper<SysRouterAuth>().eq("router_id_",routerId));
    }

}
